﻿using MemberManager.Common.Classes;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace MemberManager.UI
{
    public partial class MemberManager : Form
    {
        BackgroundWorker bgw = null;
        ManualResetEvent manualReset = new ManualResetEvent(true);

        public MemberManager()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 切换选择管理员  显示隐藏密码输入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbx_isCreateMaster_CheckedChanged(object sender, EventArgs e)
        {
            lab_domainMaster.Enabled = cbx_isCreateMaster.Checked;
            txt_domainMasterPwd.Enabled = cbx_isCreateMaster.Checked;
        }

        /// <summary>
        /// 点击操作按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Operation_Click(object sender, EventArgs e)
        {
            try
            {
                if (btn_Operation.Text == "开始")
                {
                    btn_Stop.Enabled = true;
                    btn_Operation.Text = "暂停";

                    progress_account.Maximum = Convert.ToInt32(num_accountNumber.Value);

                    //后台批量生成帐号
                    bgw = new BackgroundWorker();

                    bgw.DoWork += Bgw_DoWork;
                    bgw.RunWorkerCompleted += Bgw_RunWorkerCompleted;
                    bgw.ProgressChanged += Bgw_ProgressChanged;
                    bgw.WorkerReportsProgress = true;
                    bgw.WorkerSupportsCancellation = true;
                    bgw.RunWorkerAsync(new MailModel()
                    {
                        TrunCount = progress_account.Maximum,
                        StartNumber = string.IsNullOrEmpty(txt_startNumber.Text) ? 0 : Convert.ToInt32(txt_startNumber.Text),
                        AccountPwd = txt_accountPwd.Text,
                        DomainName = txt_domainName.Text,
                        IsDefaultFloder = cbx_accountDefaultFolder.Checked,
                        IsMaster = cbx_isCreateMaster.Checked,
                        MasterPwd = txt_domainMasterPwd.Text,
                        Prefix = txt_prefix.Text
                    });

                }
                else if (btn_Operation.Text == "暂停")
                {
                    //如果点击暂停
                    btn_Operation.Text = "继续";
                    manualReset.Reset();//暂停当前线程的工作，发信号给waitOne方法 
                }
                else if (btn_Operation.Text == "继续")
                {
                    btn_Operation.Text = "暂停";
                    manualReset.Set();
                }
            }
            catch(Exception ex)
            {

            }
        }

        private void Bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progress_account.Value = e.ProgressPercentage;
        }

        private void Bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            btn_Stop.Enabled = false;
            btn_Operation.Text = "开始";
            progress_account.Value = 0;
            manualReset.Set();
        }

        private void Bgw_DoWork(object sender, DoWorkEventArgs e)
        {
            MailModel model = e.Argument as MailModel;

            for (int i = model.StartNumber; i < model.TrunCount + model.StartNumber; i++)
            {
                manualReset.WaitOne();
                if (bgw.CancellationPending)
                {
                    e.Cancel = false;
                    break;
                }

                try
                {
                    //如果是首条  执行创建域功能
                    if (i == model.StartNumber)
                    {
                        DomainHelper dh = new DomainHelper();
                        if (model.IsMaster)
                            dh.AddDomain(model.DomainName, true, model.MasterPwd);
                        else
                            dh.AddDomain(model.DomainName);
                    }

                    //执行创建帐号
                    AccountHelper ah = new AccountHelper();
                    ah.AddAccount(model.DomainName, model.Prefix + i, model.AccountPwd, hMailServer.eAdminLevel.hAdminLevelNormal, model.IsDefaultFloder);

                }
                catch(Exception ex)
                {

                }


                bgw.ReportProgress(i - model.StartNumber + 1);

                Thread.Sleep(1000);
            }
        }

        /// <summary>
        /// 停止按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Stop_Click(object sender, EventArgs e)
        {
            manualReset.Set();
            bgw.CancelAsync();
        }


        class MailModel
        {
            public int TrunCount { get; set; }
            public int StartNumber { get; set; }
            public string DomainName { get; set; }
            public string Prefix { get; set; }
            public string AccountPwd { get; set; }
            public bool IsMaster { get; set; }
            public string MasterPwd { get; set; }
            public bool IsDefaultFloder { get; set; }

        }

        private void btn_output_Click(object sender, EventArgs e)
        {
            //根据选择的下拉域名  导出指定域的所有用户
            if (!string.IsNullOrEmpty(cbox_outputDomain.Text) && cbox_outputDomain.SelectedIndex>=0)
            {
                //获取列表
                AccountHelper ah = new AccountHelper();
                List<Models.AccountInfo> list = ah.GetList(cbox_outputDomain.Text);


                //将列表的数据导出到指定位置
                CSVHelper ch = new CSVHelper();
                if(ch.SaveDataToCSVFile(list, this.lab_outputPath.Text))
                {
                    //保存成功
                    lab_outputPath.Text = "";
                    cbox_outputDomain.SelectedIndex = -1;
                }
                else
                {
                    MessageBox.Show("错误");
                }
            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //如果切换到导入导出
            if(tabControl1.SelectedIndex==1)
            {
                if(string.IsNullOrEmpty(txt_hmailPwd.Text))
                {
                    MessageBox.Show("填写密码");
                    txt_hmailPwd.Focus();
                }

                //加载域名列表
                DomainHelper dh = new DomainHelper();
                cbox_outputDomain.Items.AddRange(dh.GetList().ToArray());

                
            }
        }

        private void btn_chooseOutputPath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog path = new FolderBrowserDialog();
            path.ShowDialog();
            this.lab_outputPath.Text = path.SelectedPath + "member.csv";
        }

        private void btn_input_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Multiselect = true;
            fileDialog.Title = "请选择文件";
            fileDialog.Filter = "数据文件(*csv)|*.csv"; //设置要选择的文件的类型
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                string file = fileDialog.FileName;//返回文件的完整路径   
                //读取csv 获得要添加用户的文本
                CSVHelper ch = new CSVHelper();
                List<Models.AccountInfo> list = ch.ReadDataFromCSVFile(file);
                if(list!=null && list.Count>0)
                {
                    //批量导入数据库
                    //执行创建帐号
                    AccountHelper ah = new AccountHelper();
                    DomainHelper dh = new DomainHelper();
                    List<string> doList = new List<string>();
                    foreach(Models.AccountInfo tempModel in list)
                    {
                        if(!doList.Contains(tempModel.DomainName))
                        {
                            doList.Add(tempModel.DomainName);
                            dh.AddDomain(tempModel.DomainName);
                        }

                        ah.AddAccount(tempModel.DomainName
                            , tempModel.AccountName.IndexOf("@")>0 ? tempModel.AccountName.Substring(0, tempModel.AccountName.IndexOf("@")) : tempModel.AccountName
                            , tempModel.AccountPwd
                            , hMailServer.eAdminLevel.hAdminLevelNormal
                            , tempModel.IsDefaultFloder);
                    }
                }

                //导入完毕
                MessageBox.Show("导入完毕");
            }
        }

        private void btn_verification_Click(object sender, EventArgs e)
        {
            //验证登录是否成功
            Global.host = "127.0.0.1";
            Global.hmname = txt_hmailName.Text;
            Global.hmpwd = txt_hmailPwd.Text;

            //验证
            BaseHelper bh = new BaseHelper();
            if(bh.Verification())
            {
                tabControl1.Enabled = true;
                txt_hmailPwd.Enabled = false;
                txt_hmailName.Enabled = false;
                btn_verification.Enabled = false;
            }
            else
            {
                MessageBox.Show("验证失败");
            }
        }
    }
}
